#include "threadPool.h"

int main(int argc,char *argv[])
{
    //解析server.conf放入conf字符串数组
    char **conf = tokenConf(argv[1]);
    //声明父进程和子进程通信的管道
    pipe(exitPipe);
    //父进程要做这些
    if(fork() != 0)
    {
        printf("pid = %d\n",getpid());
        close(exitPipe[0]);
        //父进程阻塞在这里
        signal(SIGUSR1,handler);
        wait(NULL);
        exit(0);
    }

   //test!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    char md5_str[MD5_STR_LEN + 1];
    int ret_md5 = Compute_file_md5(argv[1], md5_str);
	if (0 == ret_md5)
	{
		printf("[file - %s] md5 value:\n", argv[1]);
		printf("%s\n", md5_str);
	}
   //
   //
   //
   //
   //



    //以下是子进程（主线程）做的事情
    //子进程额外需要监听exitPipe的读端
    close(exitPipe[1]);    
    //连接sql
    mysql = mysqlConnect("root","123456"); 
    //准备线程池的数据结构
    threadPool_t threadPool;
    int workernum = atoi(conf[2]);
    //printf("%d",workernum);
    //初始化线程池
    threadPoolInit(&threadPool,workernum);
    //创建子进程
    makeWorker(&threadPool);
    
    int sockfd;//初始化tcp连接
    tcpInit(conf[0],conf[1],&sockfd);

    int epfd = epoll_create(1);
    epollAdd(epfd,sockfd);//监听sockfd
    epollAdd(epfd,exitPipe[0]);

    struct epoll_event readyset[2];
    while(1)
    {
        int readynum = epoll_wait(epfd,readyset,2,-1);
        for(int i = 0;i<readynum;++i)
        {
            if(readyset[i].data.fd == sockfd)
            {
                int netfd = accept(sockfd,NULL,NULL);
                pthread_mutex_lock(&threadPool.taskQueue.mutex);
                taskEnQueue(&threadPool.taskQueue, netfd);
                printf("main thred send a task\n");
                pthread_cond_signal(&threadPool.taskQueue.cond);
                pthread_mutex_unlock(&threadPool.taskQueue.mutex);
            }
            else if(readyset[i].data.fd == exitPipe[0])
            {
                printf("threadPool is going to exit\n");
                pthread_mutex_lock(&threadPool.taskQueue.mutex);
                threadPool.exitFlag = 1;
                pthread_cond_broadcast(&threadPool.taskQueue.cond);
                pthread_mutex_unlock(&threadPool.taskQueue.mutex);
                for(int j=0;j<workernum;++j)
                {
                    pthread_join(threadPool.tidArr[j],NULL);
                }
                printf("main thread is closing\n");
                exit(0);


            }
        }
    }
    mysql_close(mysql);
    return 0;

}
